<template>
    <div class="score-overview">
      <div class="overview-section" id="Homework-score">
        <!-- 整体概览 -->
        <div class="overview-content">
          <!-- 提交情况 -->
          <div class="submit-info" v-if="overviewData&&overviewData.length>0">
              <!-- 单个班级情况 -->
            <div>
              <span v-if="overviewData&&overviewData.length>0" style="font-weight:bold;">本次作业/测验：</span>满分<i>{{ overviewData[1].fullScore }}分</i>，
            </div>
            <div v-for="item in scoreallgrade">
              全体最高分<i>{{item.highestScore}}分</i>，
              全体平均分<i>{{item.AvgScore}}分</i>，
              优秀率<i>{{item.excellentPercent}}%</i>/
              及格率<i>{{item.passPercent}}%</i>/
              中位数为<i>{{ item.medianScore }}分</i>/
              标准差为<i>{{ item.stdDeviation }}</i>
            </div>
            <div v-for="item in scoreallclass">
              {{item.name}}班最高分<i>{{ item.highestScore }}分</i>，
              班平均分<i>{{ item.avgScore }}分</i>，
              优秀率<i>{{ item.excellentPercent }}%</i>/
              及格率<i>{{ item.passPercent}}%</i>/
              中位数为<i>{{ item.medianScore}}分</i>/
              标准差为<i>{{ item.stdDeviation }}</i>
              本班<i>{{ item.totalCount }}人</i>，
              扫描<i>{{ item.submitCount }}人</i>，
              缺少<i>{{ item.totalCount - item.submitCount }}人</i>
              <b v-if="item.unsubmittedList.length">
                ，缺少名单：
                <!-- <i>{{ item.unsubmittedList.join('、') }}</i> -->
                 <template v-if="item.unsubmittedList.length <= 15">
                  <i>{{ item.unsubmittedList.join('、') }}</i>
                </template>
                <template v-else>
                  <i v-if="!item.showAll">{{ getTruncatedList(item.unsubmittedList) }}...</i>
                  <i v-else>{{ item.unsubmittedList.join('、') }}</i>
                  <a href="javascript:;" @click="toggleShowAll(item)" style="margin-left: 5px; color: #1890ff;">
                    {{ item.showAll ? '收起' : '展开' }}
                  </a>
                </template>
              </b>
            </div>
          </div>
        </div>
      </div>
      <!-- 原始分成绩及排名-->
      <div class="rank-change anchor-offset" id="fluctuate-student">
         <!-- <h3 class="header-with-select">原始分成绩及排名</h3> -->
         <div style="display: flex;align-items: center;justify-content: space-between;">
            <h3 class="header-with-select">原始分成绩及排名</h3>
            <div @click="reportCardExport" class="derivedBtn" style="margin-bottom: 14px;margin-top: 24px;cursor: pointer;color: #295CFF;">导出</div>
          </div>
        <el-table :data="originalScoreRankinglist" border v-loading="loadingRankChange"
        stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B',fontWeight:'500' }"
        class="custom-table"
        tooltip-effect="dark"
        style="width: 100%">
          <el-table-column prop="class" label="班级 " align="center"/>
          <el-table-column prop="studentNo" label="考号 " align="center"/>
          <el-table-column prop="name" label="姓名 " align="center"/>
          <el-table-column label="总得分" align="center">
            <el-table-column prop="totalScore" label="总分 " align="center"/>
            <el-table-column prop="overallRank" label="全体排名 " align="center"/>
            <el-table-column prop="classRank" label="班级排名 " align="center"/>
            <el-table-column prop="objectiveScore" label="客观题总分 " align="center"/>
            <el-table-column prop="subjectiveScore" label="主观题总分 " align="center"/>
          </el-table-column>
          <el-table-column label="客观题得分" align="center">
            <el-table-column 
              v-for="(question, index) in originalScoreRankinglist[0].objectiveMap || []"
              :key="question.questionNum"
              :label="String(question.questionNum)">
                <template slot-scope="scope">
                    {{ scope.row.objectiveMap[index].score }}
                </template>
            </el-table-column>
            <!-- <el-table-column v prop="name" label="单选题1 " align="center"/>
            <el-table-column prop="name" label="单选题1 " align="center"/> -->
          </el-table-column>
          <el-table-column label="主观题得分" align="center">
            <el-table-column 
              v-for="(question, index) in originalScoreRankinglist[0].subjectiveMap || []"
              :key="question.questionNum"
              :label="String(question.questionNum)">
                <template slot-scope="scope">
                    {{ scope.row.subjectiveMap[index].score }}
                </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </template>
  
  <script>
  import { getScoreOverview,originalScoreRanking } from '@/api/grade'
  import { scoreDetailsExcels } from '@/api/score.js'
  export default {
    name: 'ScoreOverview',
    props: {
      examId: {
        type: [String, Number],
        required: true
      },
      classIds: {
        type:String,
        required: true
      },
      classIds1: {
        type: [Array],
        required: true
      },
    },
    data() {
      return {
        queryParams: {
          examId: '',
          classIds: ''
        },
        loading: false,
        loadingScoreDetails: false,
        loadingErrorQuestions: false,
        hasData: false,
        overviewData: {
          examHighestScore: 0,
          examAvgScore: 0,
          examExcellentPercent: 0,
          examPassPercent: 0,
          examMedianScore: 0,
          examStdDeviation: 0,
          fullScore: 0,
          highestScore: 0,
          avgScore: 0,
          excellentPercent: 0,
          passPercent: 0,
          medianScore: 0,
          stdDeviation: 0,
          totalCount: 0,
          submitCount: 0,
          unsubmittedList: []
        },
        scoreDetails: [],
        objectiveQuestionNums: [],
        subjectiveQuestionNums: [],
        errorQuestions: [],
        errorQuestionRate: 40,
        errorQuestionsError: '',
        loadingRankChange: false,
        rankChangeError: '',
        rankChangeData: [],
        hasThirdExam: false,
        scoreallgrade:[],
        scoreallclass:[],
        originalScoreRankinglist:[]
      }
    },
  
    methods: {
       getTruncatedList(list) {
        return list.slice(0, 15).join('、');
      },
      toggleShowAll(item) {
        this.$set(item, 'showAll', !item.showAll);
      },
      // formatNumber(num) {
      //   if (num === undefined || num === null) return '--'
      //   return Number(num).toFixed(2)
      // },
  
      // 处理查询
      // async handleQuery() {
      //   if (!this.queryParams.examId || !this.queryParams.classId) {
      //     this.$message.warning('请输入批次ID和班级ID')
      //     return
      //   }
  
      //   this.hasData = false
      //   await this.loadAllData()
      // },
  
      // 处理重置
      // handleReset() {
      //   this.queryParams = {
      //     examId: '',
      //     classId: ''
      //   }
      //   this.hasData = false
      //   this.resetData()
      // },
  
      // 重置数据
      // resetData() {
      //   this.overviewData = {
      //     fullScore: 0,
      //     highestScore: 0,
      //     avgScore: 0,
      //     excellentPercent: 0,
      //     passPercent: 0,
      //     medianScore: 0,
      //     stdDeviation: 0,
      //     totalCount: 0,
      //     submitCount: 0,
      //     unsubmittedList: []
      //   }
      //   this.scoreDetails = []
      //   this.objectiveQuestionNums = []
      //   this.subjectiveQuestionNums = []
      //   this.errorQuestions = []
      //   this.errorQuestionsError = ''
      //   this.rankChangeData = []
      // },
  
      // // 加载所有数据
      // async loadAllData() {
      //   try {
      //     this.loading = true
      //     await Promise.all([
      //       this.loadErrorQuestions(),
      //       this.loadData(),
      //       this.loadScoreDetails(),
      //       this.loadRankChange()
      //     ])
      //     this.hasData = true
      //   } catch (error) {
      //     console.error('加载数据失败:', error)
      //     this.$message.error('加载数据失败，请检查输入的ID是否正确')
      //     this.hasData = false
      //   } finally {
      //     this.loading = false
      //   }
      // },
  
      // 加载成绩概览
      async loadOverview() {
        this.overviewData = []
        this.scoreallgrade = []
        this.scoreallclass = []
        try {
          const res = await getScoreOverview(
            Number(this.examId), 
            String(this.classIds)
          )
          if (res.code === 200) {
            console.info('getScoreOverview',res)
            this.overviewData = res.data
            this.scoreallgrade = res.data.filter(item=>item.type==0)
            // console.info('this.scoreallgrade',this.scoreallgrade)
            this.scoreallclass = res.data.filter(item=>item.type==1)
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
      //原始分成绩及排名
      async originalScoreRankingdata(){
        this.originalScoreRankinglist=[]
        try {
          const res = await originalScoreRanking(
            Number(this.examId), 
            String(this.classIds)
          )
          if (res.code === 200) {
            console.info('originalScoreRanking',res)
            this.originalScoreRankinglist = res.data|| []
            this.originalScoreRankinglist.forEach(item => {
              item.objectiveMap = item.objectiveMap || [];
            });
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
      reportCardExport() {
        scoreDetailsExcels(Number(this.examId), String(this.classIds)).then(res => {
        if (res.code == 200) {
          const link = document.createElement('a');
          let fileName = '原始分成绩及排名.xlsx'
          link.href = process.env.VUE_APP_BASE_APIS + res.data;
          link.download = fileName || 'file.xlsx'; // 设置默认文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      })
      },
  
      // 加载作业得分表
      // async loadScoreDetails() {
      //   try {
      //     this.loadingScoreDetails = true
      //     const res = await getScoreDetails(
      //       Number(this.examId), 
      //       Number(this.classId)
      //     )
      //     if (res.code === 200) {
      //       this.scoreDetails = res.data
      //       if (this.scoreDetails.length > 0) {
      //         const firstStudent = this.scoreDetails[0]
      //         this.objectiveQuestionNums = Object.keys(firstStudent.objectiveMap || {})
      //           .sort((a, b) => Number(a) - Number(b))
      //         this.subjectiveQuestionNums = Object.keys(firstStudent.subjectiveMap || {})
      //           .sort((a, b) => Number(a) - Number(b))
      //       }
      //     } else {
      //       throw new Error(res.message)
      //     }
      //   } catch (error) {
      //     console.error('加载作业得分表失败:', error)
      //     throw error  // 向上传递错误
      //   } finally {
      //     this.loadingScoreDetails = false
      //   }
      // },
  
      // 加载高频错题统计
      // async loadErrorQuestions() {
      //   try {
      //     this.loadingErrorQuestions = true
      //     this.errorQuestionsError = ''
          
      //     const res = await getErrorQuestions(
      //       Number(this.examId), 
      //       Number(this.classId), 
      //       this.errorQuestionRate
      //     )
      //     if (res.code === 200) {
      //      res.data.forEach(item => {
      //         // 初始化三个数组来存储不同类型的名单
      //         item.errorlistname = [];
      //         item.correctlistname = [];
      //         item.dimidiatelistname = [];
            
      //          // 遍历 rights 数组
      //           item.answerRight.rights.forEach(right => {
      //             const students = right.studentList.join(', '); // 将学生名字用逗号连接成一个字符串
      //             switch (right.isRight) {
      //               case "0": // 错误
      //                 item.errorlistname.push(students); // 将字符串添加到 errorlistname
      //                 break;
      //               case "1": // 正确
      //                 item.correctlistname.push(students); // 将字符串添加到 correctlistname
      //                 break;
      //               case "2": // 半对
      //                 item.dimidiatelistname.push(students); // 将字符串添加到 dimidiatelistname
      //                 break;
      //               default:
      //                 break;
      //             }
      //           });
              
      //           // 将数组中的字符串用逗号连接成一个完整的字符串
      //           item.errorlistname = item.errorlistname.join(', ');
      //           item.correctlistname = item.correctlistname.join(', ');
      //           item.dimidiatelistname = item.dimidiatelistname.join(', ');
      //       });
      //       this.errorQuestions = res.data || []
      //       console.info('this.errorQuestions',this.errorQuestions)
      //       if (this.errorQuestions.length === 0) {
      //         this.errorQuestionsError = `暂无得分率低于${this.errorQuestionRate}%的题目`
      //       }
      //     } else {
      //       this.errorQuestionsError = res.message || '获取高频错题统计失败'
      //       throw new Error(this.errorQuestionsError)
      //     }
      //   } catch (error) {
      //     console.error('获取高频错题统计失败:', error)
      //     throw error  // 向上传递错误
      //   } finally {
      //     this.loadingErrorQuestions = false
      //   }
      // },
  
      // async loadRankChange() {
      //   try {
      //     this.loadingRankChange = true
      //     this.rankChangeError = ''
      //     const res = await getRankChange(Number(this.examId), Number(this.classId))
      //     if (res.code === 200) {
      //       this.rankChangeData = res.data.changes || []
      //       this.hasThirdExam = this.rankChangeData.some(item => item.score3 !== undefined)
      //     } else {
      //       throw new Error(res.message)
      //     }
      //   } catch (error) {
      //     console.error('加载成绩波动数据失败:', error)
      //     this.rankChangeError = '加载成绩波动数据失败'
      //     throw error  // 向上传递错误
      //   } finally {
      //     this.loadingRankChange = false
      //   }
      // }
    },
  
    mounted() {
      this.loadOverview()
      this.originalScoreRankingdata()
    },
    watch: {
      classIds1: {
        handler(newVal, oldVal) {
          console.info(newVal+'-----'+oldVal)
          if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;
          console.log('classIds 变化:', oldVal, '→', newVal);
          this.classIds = newVal.join(',');
          this.loadOverview();
          this.originalScoreRankingdata();
        },
        immediate: true,  // 立即触发一次
        deep: true       // 字符串不需要深度监听
      },
      examId: {
        handler(newVal, oldVal) {
          console.info(newVal+'-----'+oldVal)
          if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;
          this.loadOverview();
          this.originalScoreRankingdata();
        },
        immediate: true,  // 立即触发一次
        deep: true       // 字符串不需要深度监听
      }
    }
    // beforeDestroy() {
    //   if (this.boxPlotChart) {
    //     this.boxPlotChart.dispose()
    //   }
    // }
  }
  </script>
  
  <style scoped>
  .score-overview{
      background: #FFFFFF;
      box-shadow: 0 12px 16px 0 #5572921a;
      border-radius:0 0 10px 10px;
      padding:10px 24px 24px;
  }
  .query-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .query-form {
    display: flex;
    align-items: center;
  }
  
  .overview-section,
  .score-details,
  .score-analysis,
  .rank-change,
  .error-questions {
    background: #fff;
    border-radius: 4px;
  }
  
  .overview-content {
      box-sizing: border-box;
    background: #295cff0a;
    border: 1px solid #295cff33;
    border-radius: 10px;
    padding:18px 24px 0;
    font-size:14px;
  }
  
  .submit-info {
    margin-bottom: 16px;
    line-height: 1.8;
    color:#8E96A4
  }
  .submit-info span{
      color:#295CFF
  }
  .submit-info i{
      color:#5B6371;
      font-style: normal;
  }
  .submit-info b{
      font-style:normal;
      font-weight: normal;
  }
  .class-info {
    margin-top: 8px;
    text-indent: 2em;
    line-height: 1.8;
  }
  .score-row {
    display: flex;
    gap: 16px;
    justify-content: center;
  }
  .score-item {
    min-width: 40px;
    text-align: center;
  }
  .question-numbers {
    display: flex;
    gap: 16px;
    justify-content: center;
    margin-top: 8px;
    font-size: 12px;
  }
  .question-numbers span {
    min-width: 40px;
    text-align: center;
  }
  .rank-change {
    background: #fff;
    border-radius: 4px;
  }
  .change-info {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
  .change-info .el-tag {
    min-width: 80px;
  }
  .error-questions {
    background: #fff;
    border-radius: 4px;
  }
  .el-tag {
    width: 80px;
    text-align: center;
  }
  .analysis-content {
    margin-top: 16px;
    line-height: 1.8;
  }
  .header-with-select{
      font-size:16px;
      color:#2A303B;
      margin-bottom:14px;
      margin-top:24px;
  }
  .custom-table {
    width: 100%;
    border: 1px solid rgba(216,228,240,1);
    border-radius:10px;
    border-right: none;
    border-bottom:none;
  }
  
  /* 自定义表格内部元素的样式 */
  .custom-table >>> .el-table__header-wrapper th {
    background-color: rgb(232, 240, 250);
    height:42px;
    padding:0;
    text-align: center;
    font-weight:normal
  }
  .custom-table >>> .el-table__row td {
    height:42px;
    padding:0;
    text-align: center;
    border-bottom:none;
    border-right:solid 1px rgba(216,228,240,1);
  }
  .el-table .warning-row {
      background: #ffffff;
   }
  .el-table .success-row {
      background: #D8E4F0;
  }
  .anchor-offset {
    scroll-margin-top: 60px;
  }
  .derivedBtn {
    padding: 2px 12px;
    border-radius: 100px;
    color: #295CFF;
    border: 1px solid #295CFF;
    background: #295cff0f;
  }
  </style> 